package authority.servlet;

import authority.comm.Lay;
import authority.entity.Dept;
import authority.entity.User;
import authority.service.DeptService;
import authority.util.CommonUtil;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/deptServlet")
public class DeptServlet extends HttpServlet {

    private DeptService service = new DeptService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        String opr = request.getParameter("opr");
        if ("query".equals(opr)) {//查询所有的部门
            //接受参数
            String page = request.getParameter("page");
            String limit = request.getParameter("limit");//显示条数
            Integer p = CommonUtil.objectToInteger(page);
            Integer li = CommonUtil.objectToInteger(limit);
            //定义layui返回数据
            Lay lay = new Lay();
            lay.setPage(p);
            lay.setLimit(li);
            //执行查询，封装数据
            lay = service.queryDept(lay, null);
            //最后输出json数据
            out.print(JSON.toJSONString(lay));
        }
        if ("addDept".equals(opr)){
            String name=request.getParameter("name");
            String detail=request.getParameter("detail");
            Dept dept=new Dept();
            dept.setName(name);
            dept.setDetail(detail);
            out.print( JSON.toJSONString( service.addDept(dept,(User)request.getSession().getAttribute("user"))));
        }
        out.close();
    }
}
